package com.fengq1.timeaxis.core;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 页面dto
 */
@Data
@ApiModel("分页DTO")
public class PageDTO implements Serializable {

    @NotNull
    @Min(value = 1)
    @ApiModelProperty(value = "第几页 从1开始", required = true)
    private Integer pageNo; // 第几页 从1开始

    @NotNull
    @Min(value = 1)
    @ApiModelProperty(value = "每页记录数", required = true)
    private Integer pageSize;

    @ApiModelProperty("排序字段名")
    private String column;

    @ApiModelProperty("排序方式")
    private String order;

    public String convertColumn(String column) {
        StringBuilder result = new StringBuilder();
        for (char c : column.toCharArray()) {
            if (Character.isUpperCase(c)) {
                result.append("_");
                result.append(Character.toLowerCase(c));
            } else
                result.append(c);
        }
        return result.toString();
    }

    public void order(String column, String order, LambdaQueryWrapper lambdaQueryWrapper) {
        if (StrUtil.isNotBlank(this.column)) {
            column = this.column;
            order = this.order;
        }
        if (StrUtil.isNotBlank(column)) {
            String[] columns = column.split(",");
            String[] orders = order.split(",");
            StringBuilder orderSql = new StringBuilder();
            for (int i = 0; i < columns.length; i++) {
                if (i == 0)
                    orderSql.append("order by ");
                orderSql.append(convertColumn(columns[i]))
                        .append(" ")
                        .append(orders[i]);
                if (i != columns.length - 1)
                    orderSql.append(" , ");
            }
            lambdaQueryWrapper.last(orderSql.toString());
        }
    }


    public void order(LambdaQueryWrapper lambdaQueryWrapper) {
        order(this.column, this.order, lambdaQueryWrapper);
    }
}
